package com.example.hcd.functionactivity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.hcd.R;
import com.example.hcd.adapt.OverTimeAdapt;
import com.example.hcd.datamanage.OverTimeData;
import com.example.hcd.internet.InternetKeep;
import com.example.hcd.internet.LinkHelp;
import com.example.hcd.internet.URLS;
import com.example.hcd.tool.MyLoadingDialog;
import com.example.hcd.tool.ToastHelp;
import com.example.hcd.tool.XListView;
import com.example.hcd.tool.XListView.IXListViewListener;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class OffListActivity extends BaseActivity implements OnClickListener,OnItemClickListener,IXListViewListener{

	private OffListActivity context;
	private LayoutInflater inflater;
	private View main_view;
	private TextView title_content;

	private XListView list;
	
	private int currentPage = 1;
	
	private OverTimeAdapt adapt;
	private String type;



	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		mPageName = "OffListActivity";
		context = this;
		inflater = LayoutInflater.from(this);
		main_view = inflater.inflate(R.layout.my_task_list_view, null);
		setContentView(main_view);
		type = getIntent().getStringExtra("TASK_TYPE");
		title_content = (TextView) findViewById(R.id.title_content);
		list = (XListView) findViewById(R.id.lists);
		list.setPullLoadEnable(true);
		list.setXListViewListener(this);
		list.setOnItemClickListener(this);
		//
		// 返回键
		ImageView backBtn = (ImageView) findViewById(R.id.title_bar_btn_left);
		// 刷新
		ImageView refreshBtn = (ImageView) findViewById(R.id.title_bar_btn_right);
		backBtn.setOnClickListener(context);
		refreshBtn.setOnClickListener(context);
		
		initList();
		
	}
	
	public void initList() {
		LoadTaskInfoList list = new LoadTaskInfoList(context,1);
		list.execute();

	}

	public void refreshBorrowList()
	{
		ArrayList<OverTimeData> data = InternetKeep.getInstence().getOvertimeListCatch();
		adapt.addList(data);
		//list.setAdapter(adapt);
	}
	
	public void initBorrowItem()
	{
		if (type.equals("my_off_list")) 
		{
			title_content.setText("我的调休列表");
		}else if (type.equals("all_off_list")) 
		{
			title_content.setText("调休列表统计");
		}
		
		adapt = new OverTimeAdapt(context);
		adapt.setisOff(true);
		ArrayList<OverTimeData> data = InternetKeep.getInstence().getOvertimeListCatch();
		adapt.setList(data);
		list.setAdapter(adapt);
		
		if(data.size()==0)
		{
			list.removeFooterViews();
		}
	}
	
	

	private class LoadTaskInfoList extends AsyncTask<String, Integer, String> {

		private Context context;
		private int index;
		private MyLoadingDialog dialog;
		public LoadTaskInfoList(Context context, int index) {
			this.context = context;
			this.index = index;
		}

		@Override
		protected void onPreExecute() {
			dialog = new MyLoadingDialog(context, null, "加载中...", false);
			dialog.setPullToRefreshListView(list);
		}

		@Override
		protected String doInBackground(String... params) {
			String result = null;
			HttpResponse response = null;
			BufferedReader reader = null;
			try {
				ArrayList<NameValuePair> vs = new ArrayList<NameValuePair>();
				//vs.add(new BasicNameValuePair("taskId", taskId));
				vs.add(new BasicNameValuePair("currentPage", ""+currentPage));
	
				response = LinkHelp.post(URLS.getTaskInfoByType(type), vs, false);
				
				if (response != null) {
					StatusLine line = response.getStatusLine();
					if (line.getStatusCode() == 200) {
						reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
						StringBuilder sb = new StringBuilder();
						for (String s = reader.readLine(); s != null; s = reader.readLine()) {
							sb.append(s);
						}
						result = sb.toString();
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (reader != null) {
					try {
						reader.close();
						
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			return result;
		}

		@Override
		protected void onPostExecute(String result) {
			dialog.dimiss();
			if(dialog.mCancel)
			{
				return;
			}
			
			if (!TextUtils.isEmpty(result)) {

				if (result.contains("error")) 
				{
					onLoad();
					
					try {
						JSONObject obj = new JSONObject(result);
						String msg = obj.getString("msg");
						ToastHelp.doToast(context, msg);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} else {

					if(index >1)
					{
						if (type.equals("my_off_list")||type.equals("all_off_list")) 
						{
							InternetKeep.getInstence().ParseOverTimeList(result);
							refreshBorrowList();
						}
						onLoad();
						
					}else
					{
						InternetKeep.getInstence().clearCacheData();
						SimpleDateFormat format = new SimpleDateFormat(
								"yyyy年MM月dd日  HH:mm");
						String date = format.format(new Date());
						if (type.equals("my_off_list")||type.equals("all_off_list")) 
						{
							InternetKeep.getInstence().clearCacheData();
							InternetKeep.getInstence().ParseOverTimeList(result);
							initBorrowItem();
						}
						onLoad();
						
					}
					
					if(InternetKeep.getInstence().isHaveNextPage)
					{
						list.removeFooterViews();
					}
	
					
				}

			}else
			{
				list.stopRefresh();
				list.stopLoadMore();
					ToastHelp.doToast(context, "网络异常");
				
			}
		}

	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		int id = arg0.getId();
		switch (id) {
		case R.id.title_bar_btn_left:
			finish();
			break;
			
		case R.id.title_bar_btn_right:
			new LoadTaskInfoList(context, currentPage=1).execute();
			break;

		default:
			break;
		}
	
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		OverTimeData data = adapt.getItem(arg2-1);
		Intent intent = new Intent(context, TaskInfo.class);
		intent.putExtra("taskId", data.getID());
		intent.putExtra("processId", data.getProcessInstanceId());
		intent.putExtra("TASK_TYPE", "daysOff");
		intent.putExtra("IS_TASK_TODO", false);
		startActivity(intent);
	
	}

	@Override
	public void onRefresh() {
		list.addFooterViews();
		new LoadTaskInfoList(context, currentPage=1).execute();
				
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		if(!InternetKeep.getInstence().isHaveNextPage)
		{
			currentPage++;
			new LoadTaskInfoList(context, currentPage).execute();
		}else
		{
			Toast.makeText(context, "已经到最后", Toast.LENGTH_SHORT).show();
			onLoad();
		}
	}
	
	private void onLoad() {
		SimpleDateFormat format = new SimpleDateFormat(
				"yyyy年MM月dd日  HH:mm");
		String date = format.format(new Date());
		list.stopRefresh();
		list.stopLoadMore();
		list.setRefreshTime(date);
	}

}
